package com.beagle.njddapp.ui.presenter;

import android.content.Context;

import com.beagle.njddapp.base.ApiService;
import com.beagle.njddapp.base.BaseApplication;
import com.beagle.njddapp.base.BasePresenter;
import com.beagle.njddapp.base.NjOwnerApiService;
import com.beagle.njddapp.base.RetrofitHttp;
import com.beagle.njddapp.bean.JszBean;
import com.beagle.njddapp.bean.owner.NongJiBean;
import com.beagle.njddapp.bean.UploadBean;
import com.beagle.njddapp.bean.ZdBean;
import com.beagle.njddapp.net.BaseHttpResponse;
import com.beagle.njddapp.net.BaseOilHttpListResponse;
import com.beagle.njddapp.net.BaseZdHttpListResponse;
import com.beagle.njddapp.net.HttpResponseObserver;
import com.beagle.njddapp.net.RxSchedulers;
import com.beagle.njddapp.ui.view.DeviceAddView;
import com.beagle.njddapp.utils.Utils;
import com.blankj.utilcode.util.LogUtils;
import com.google.gson.Gson;

import java.io.File;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * @author hxx
 * @date 2021-03-02 22:33
 */
public class DeviceAddPresenter extends BasePresenter<DeviceAddView> {
    private NjOwnerApiService njOwnerApiService;
    private ApiService apiService;

    public DeviceAddPresenter() {
        retrofit2.Retrofit retrofit = RetrofitHttp.provideRetrofit();
        //获取接口对象
        njOwnerApiService = retrofit.create(NjOwnerApiService.class);
        apiService = retrofit.create(ApiService.class);

    }

    /**
     *
     * @param nongJiBean
     * @param isNj  是否无牌
     */
    public void addDevice(NongJiBean nongJiBean,boolean isNj) {
        Gson gson = new Gson();
        String strEntity = gson.toJson(nongJiBean);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);
        if (isNj){
            njOwnerApiService.addMeshBaseTemp(body).compose(RxSchedulers.compose()).subscribe(new HttpResponseObserver<BaseOilHttpListResponse>() {


                @Override
                public void success(BaseOilHttpListResponse baseOilHttpListResponse) {
                    LogUtils.d("success");
                    getView().addSuccess();

                }

                @Override
                public void error(int code, String message) {
                    LogUtils.d("error");
                    getView().onError(message);

                }
            });
        }else {
            njOwnerApiService.addMeshBase(body).compose(RxSchedulers.compose()).subscribe(new HttpResponseObserver<BaseOilHttpListResponse>() {


                @Override
                public void success(BaseOilHttpListResponse baseOilHttpListResponse) {
                    LogUtils.d("success");
                    getView().addSuccess();

                }

                @Override
                public void error(int code, String message) {
                    LogUtils.d("error");
                    getView().onError(message);

                }
            });
        }


    }

    public void queryDictList(String type, String parentId) {
        Gson gson = new Gson();
        HashMap<String, String> paramsMap = new LinkedHashMap<>();
        paramsMap.put("type", type);
        paramsMap.put("parentId", parentId);
        String strEntity = gson.toJson(paramsMap);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);
        paramsMap.clear();
        njOwnerApiService.queryDictList(body).compose(RxSchedulers.compose()).subscribe(new HttpResponseObserver<BaseZdHttpListResponse<ZdBean>>() {


            @Override
            public void success(BaseZdHttpListResponse<ZdBean> zdHttpListResponse) {
                LogUtils.d("success");
                if (zdHttpListResponse.items!=null){
                    getView().showZd(zdHttpListResponse.items);
                }else {
                    getView().onError("");

                }
            }

            @Override
            public void error(int code, String message) {
                LogUtils.d("error");
                getView().onError(message);
            }
        });

    }

    public void upload(String path, int index){
        Luban.with(BaseApplication.getInstance().getApplicationContext())
                .load(path)// 传人要压缩的图片列表
                .ignoreBy(100)                                  // 忽略不压缩图片的大小
                .setTargetDir(BaseApplication.getInstance().getCacheDir().getAbsolutePath())                        // 设置压缩后文件存储位置
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        String name=path.substring(path.lastIndexOf("/")+1,path.length()-1);
                        LogUtils.d(name);
                        RequestBody body=RequestBody.create(MediaType.parse("multipart/form-data"),file);//表单类型
                        MultipartBody.Builder builder = new MultipartBody.Builder()
                                .setType(MultipartBody.FORM);
                        builder.addFormDataPart("file",file.getName(),body); //添加图片数据，body创建的请求体
                        List<MultipartBody.Part> parts=builder.build().parts();
                        apiService.uploadFile(parts).compose(RxSchedulers.compose()).safeSubscribe(new HttpResponseObserver<BaseHttpResponse<UploadBean>>() {
                            @Override
                            public void success(BaseHttpResponse<UploadBean> uploadBeanBaseHttpResponse) {
                                LogUtils.d("success");
                                if (uploadBeanBaseHttpResponse.data!=null){
                                    getView().uploadSuccess(uploadBeanBaseHttpResponse.data,index);
                                }else {
                                    getView().onError("");
                                }
                            }

                            @Override
                            public void error(int code, String message) {
                                getView().onError(message);
                            }
                        });
                    }

                    @Override
                    public void onError(Throwable e) {
                        getView().onError(e.toString());

                    }
                }).launch();





    }

    public void ocrXsz(String filepath,String side){
        String url="https://dm-53.data.aliyun.com/rest/160601/ocr/ocr_vehicle.json";
        Luban.with(BaseApplication.getInstance().getApplicationContext())
                .load(filepath)// 传人要压缩的图片列表
                .ignoreBy(1400)                                  // 忽略不压缩图片的大小
                .setTargetDir(BaseApplication.getInstance().getCacheDir().getAbsolutePath())                        // 设置压缩后文件存储位置
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }
                    @Override
                    public void onSuccess(File file) {
//                        JSONObject configObj = new JSONObject();
//                        try {
//                            configObj.put("side", side);
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                        String config_str = configObj.toString();

                        Gson gson=new Gson();
                        HashMap<String,String> paramsMap=new HashMap<>();
                        paramsMap.put("image", Utils.pictureToBase64(file.getAbsolutePath()));
                        paramsMap.put("configure", "\"side\":\""+side+"\"");
                        String strEntity = gson.toJson(paramsMap);
                        RequestBody body =RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"),strEntity);
                        apiService.ocrJsz(url,body).
                                compose(RxSchedulers.compose()).safeSubscribe(new Observer<JszBean>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(JszBean jszBean) {
                                upload(file.getAbsolutePath(),4);
                            }

                            @Override
                            public void onError(Throwable e) {
                                if ("face".equals(side)){
                                    getView().onError("请上传真实的行驶证正面照片");
                                }
                            }

                            @Override
                            public void onComplete() {

                            }
                        });
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();

    }



}
